//
//  OAuthController.swift
//  weibo
//
//  Created by David on 15/11/25.
//  Copyright © 2015年 DV. All rights reserved.
//

import UIKit

class OAuthController: UIViewController,UIWebViewDelegate {

//    private var clientId = "2149927533"
//    private var appSecret = "e1acef35df1678c84bb06a0353d761fe"
//    private var redirectUri = "http://www.baidu.com"
    let webView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view = webView
        webView.delegate = self
        //加载授权
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Done, target: self, action: "backClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: .Done, target: self, action: "autologinClick")
        webView.loadRequest(NSURLRequest(URL: NetworkingTools.sharedTools.authURL))
    }
    @objc private func backClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func autologinClick(){
        let js = "document.getElementById('userId').value = 'davidf1989@sina.cn';" +
        "document.getElementById('passwd').value = 'twyuckcxy';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        //1.判断URL开头是否是回调地址,如果是 则继续加载
        if !urlString.hasPrefix(NetworkingTools.sharedTools.redirectUri){
            return true
        }
        //2.是回调地址,截取code
        //query是回调URL 问号后面的所有字符串
        if let query = request.URL!.query where query.hasPrefix("code=") {
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            //发送请求 获取accesstoken
            UserAccountViewModel.sharedTools.loadUserInfo(code).subscribeError({ (error) -> Void in
                print(error)
                }, completed: { (suessed) -> Void in
                    NSNotificationCenter.defaultCenter().postNotificationName(DVSwitchMainInterfaceNotification, object: nil)
            })
        }else
        {
            //取消
        }
        return false
    }
}
